package cn.yh.shop.product.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;

import cn.yh.shop.product.model.Attribute;
import cn.yh.shop.product.model.Brand;
import cn.yh.shop.product.model.Category;
import cn.yh.shop.product.model.Coupon;
import cn.yh.shop.product.model.Goods;
import cn.yh.shop.product.model.GoodsPrice;
import cn.yh.shop.product.model.Img;
import cn.yh.shop.product.model.Page;
import cn.yh.shop.product.model.Pakage;
import cn.yh.shop.product.model.Taste;
import cn.yh.shop.product.service.impl.AttributeServiceImpl;
import cn.yh.shop.product.service.impl.BrandSeviceImpl;
import cn.yh.shop.product.service.impl.CategoryServiceImpl;
import cn.yh.shop.product.service.impl.CouponServiceImpl;
import cn.yh.shop.product.service.impl.GoodsServiceImpl;
import cn.yh.shop.product.service.impl.ImgServiceImpl;
import cn.yh.shop.product.service.impl.PakageServiceImpl;
import cn.yh.shop.product.service.impl.TasteServiceImpl;
import cn.yh.shop.user.model.User;
import cn.yh.shop.user.model.UserComment;
import cn.yh.shop.user.model.UserOrder;
import cn.yh.shop.user.model.UserOrderItem;
import cn.yh.shop.user.service.IUserOrderService;
import cn.yh.shop.user.service.impl.UserCommentServiceImpl;
import cn.yh.shop.user.service.impl.UserCouponServiceImpl;
import cn.yh.shop.user.service.impl.UserOrderItemServiceImpl;
import cn.yh.shop.user.service.impl.UserServiceImpl;
/**
 * 
 * @Description:商品处理类
 * @author:"陈泓源"
 * @time:2016年12月14日 下午5:49:37
 */
public class GoodsAction {
	//private static Logger logger = LogManager.getLogger(GoodsAction.class);
	/**
	 * ServletRequest对象
	 */
	private HttpServletRequest request = ServletActionContext.getRequest();
	/**
	 * ServletResponse对象
	 */
	private HttpServletResponse response = ServletActionContext.getResponse();
	/**
	 * Session对象
	 */
	private HttpSession session = request.getSession();
	/**
	 * PrintWriter对象
	 */
	private PrintWriter out;
	/**
	 * 商品服务对象
	 */
	@Autowired
	private BrandSeviceImpl brandService;
	/**
	 * 类别服务对象
	 */
	@Autowired
	private CategoryServiceImpl categoryService;
	/**
	 * 商品服务对象
	 */
	@Autowired
	private GoodsServiceImpl goodsService;
	/**
	 * 图片服务对象
	 */
	@Autowired
	private ImgServiceImpl imgService;
	/**
	 * 包装服务对象
	 */
	@Autowired
	private PakageServiceImpl pakageService;
	/**
	 * 口味服务对象
	 */
	@Autowired
	private TasteServiceImpl tasteService;
	/**
	 * 用户订单服务对象
	 */
	@Autowired
	private IUserOrderService userOrderServiceImpl;
	/**
	 * 用户订单详情服务对象
	 */
	@Autowired
	private UserOrderItemServiceImpl userOrderItemService;
	/**
	 * 商品属性服务对象
	 */
	@Autowired
	private AttributeServiceImpl attributeService;
	/**
	 * 用户评论服务对象
	 */
	@Autowired
	private UserCommentServiceImpl userCommentService;
	/**
	 * 用户服务对象
	 */
	@Autowired
	private UserServiceImpl userService;
	/**
	 * 优惠券服务对象
	 */
	@Autowired
	private CouponServiceImpl couponService;
	/**
	 * 用户优惠券服务对象
	 */
	@Autowired
	private UserCouponServiceImpl userCouponService;
	/**
	 * 
	 * @Description:获取所有品牌
	 * @throws IOException
	 * void
	 * @exception:
	 * @author: "李雨"
	 * @time:2016年12月16日 下午2:26:26
	 */
	public void getCate() throws IOException {
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String brandid=request.getParameter("brandid");
		//是否获取选中品牌下的种类
		List<Category> list = categoryService.getThirdCate(brandid);
		out.print(JSON.toJSONString(list));
		out.flush();
		out.close();
	}

	/**
	 * 
	 * @Description:获取所有品牌
	 * @throws IOException
	 * void
	 * @exception:
	 * @author: "李雨"
	 * @time:2016年12月16日 下午3:13:04
	 */
	public void getBrand() throws IOException {
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		List<Brand> list = brandService.getAllBrand();
		out.print(JSON.toJSONString(list));
		out.flush();
		out.close();
	}

	/**
	 * 
	 * @Description:获取商品，根据条件，若没有任何条件即获取所有，获取页可以根据分页情况获取
	 * @throws IOException
	 * void
	 * @exception:
	 * @author: "李雨"
	 * @time:2016年12月16日 下午3:11:59
	 */
	public void getGoodsByCondi() throws IOException {
		response.setCharacterEncoding("utf-8");
		//获取品牌id
		String brandid = request.getParameter("brandid");
		//获取种类id
		String cateid = request.getParameter("cateid");
		//获取当前页数
		int index = Integer.parseInt(request.getParameter("index"));
		//获取页面大小
		int size = Integer.parseInt(request.getParameter("size"));
		//排序方式，若没有，默认排序
		String orderby=request.getParameter("order");
		//获取搜索框值
		String searchInput=request.getParameter("searchInput");
		if(orderby!=null){
			request.getSession().setAttribute("order", orderby);
		}
		Object order=request.getSession().getAttribute("order");;
		//如果排序方式不为空，则判断与上次是否操作一致，若一致，移除session中的排序键
//		if(index==1){
//			if(orderby!=null){
//				Object o=request.getSession().getAttribute("order");
//				if(orderby.equals(o)){
//					request.getSession().removeAttribute("order");
//				//否则将排序方式放入session中
//				}else{
//					request.getSession().setAttribute("order", orderby);
//				}
//				order=request.getSession().getAttribute("order");
//			}else{
//				
//			}
//		}else{
//			order=request.getSession().getAttribute("order");
//		}
		// 查询当前页的数据条件以及页码放入map
		HashMap<String, Object> map = new HashMap<String, Object>();
		//添加品牌
		map.put("brandid", brandid);
		//添加种类
		map.put("cateid", cateid);
		//排序方式
		map.put("order", order);
		//分页起始值
		map.put("minIndex", (index - 1) * size);
		//分页结束值
		map.put("maxIndex", size);
		if(searchInput!=null){
			map.put("searchInput", "%"+searchInput+"%");
		}
		//获取商品列表
		List<Goods> list = goodsService.getGoodsByCondi(map);
		//创建新的商品列表（GoodsPrice这个类名需要修改此处没有处理，里面包含了商品信息、价格、预览图片路径）
		List<GoodsPrice> plist=new ArrayList<GoodsPrice>();
		//为商品列表添加价格和图片路径字段
		for(int i=0;i<list.size();i++){
			//获取不同包装的价格，取最小值
			List<Pakage> pakge=pakageService.selectPrice(list.get(i).getId().toString());
			//这里是根据map中的条件（商品id，显示位置）查询出显示预览图片
			HashMap<String,String> imgmap=new HashMap<String,String>();
			//商品id
			imgmap.put("goodsid", list.get(i).getId().toString());
			//图片显示位置
			imgmap.put("position", "2");
			//调用获取图片的方法
			List<Img> img=imgService.getImgById(imgmap);
			//创建一个新的商品对象（商品信息、价格、预览图片路径）
			GoodsPrice gp=null;
			//是否有价格信息
			if(pakge.size()>0){
				double price=pakge.get(0).getPrice();
				//是否有图片信息
				if(img.size()>0){
					//将价格和图片路径用构造方法放入该对象
					String ipath=img.get(0).getPath().substring(img.get(0).getPath().lastIndexOf("/") + 1);
					gp=new GoodsPrice(list.get(i),price,ipath);
				}else{
					gp=new GoodsPrice(list.get(i),price,"");
				}
			//如果没有对应的价格，默认显示为0
			}else{
				if(img.size()>0){
					String ipath=img.get(0).getPath().substring(img.get(0).getPath().lastIndexOf("/") + 1, img.get(0).getPath().lastIndexOf("."));
					gp=new GoodsPrice(list.get(i),0.0,ipath);
				}else{
					gp=new GoodsPrice(list.get(i),0.0,"");
				}
			}
			//将这个新的对象放入新的列表中
			plist.add(gp);
		}
		//分页对象
		Page<GoodsPrice> page = new Page<GoodsPrice>();
		page.setPageIndex(index);
		page.setPageSize(size);
		// 查询该条件下所有数据，将条件放入map
		HashMap<String, Object> countmap = new HashMap<String, Object>();
		countmap.put("brandid", brandid);
		countmap.put("cateid", cateid);
		if(searchInput!=null){
			countmap.put("searchInput", "%"+searchInput+"%");
		}
		// 该条件下个数
		page.setDataTotal(goodsService.getGoodsByCondi(countmap).size());
		page.setPageList(plist);
		PrintWriter out = response.getWriter();
		//将page对象返回成JSON
		out.print(JSON.toJSONString(page));
		out.flush();
		out.close();
	}
	/**
	 * 
	 * @Description:搜索框跳转时页面
	 * @return
	 * String
	 * @exception:
	 * @author: "李雨"
	 * @time:2016年12月21日 上午9:21:04
	 */
	public String searchInput(){
		//获取搜索框值
		String searchInput=request.getParameter("index_none_header_sysc");
		request.setAttribute("searchInput", searchInput);
		return "success";
	}
	/**
	 * 
	 * @Description:获取热门三级分类
	 * void
	 * @exception:
	 * @author: "李雨"
	 * @throws IOException 
	 * @time:2016年12月20日 下午3:08:53
	 */
	public void getHotCategory() throws IOException{
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		List<Integer> list = goodsService.getGoodsBySaleCount();
		List<Category> catelist=new ArrayList<Category>();
		for(int i=0;(i<list.size());i++){
			Category cate=categoryService.getHotCate(list.get(i).toString());
			catelist.add(cate);
		}
		out.print(JSON.toJSONString(catelist));
		out.flush();
		out.close();
	}

	/**
	 * 
	 * @Description:获取商品详细信息
	 * @return String
	 * @exception:
	 * @author: "陈泓源"
	 * @time:2016年12月14日 下午6:10:50
	 */
	public String getGoodsByCondit() {
		String result = "fail";
		HashMap<String, String> map = new HashMap<String, String>();
		List<String> list = getPrameter("id");
		map.put("id", list.get(0));
		// 根据id获取商品信息
		Goods goods = goodsService.getGoodsByCondit(map);
		// 根据id获取图片信息
		map.clear();
		map.put("goodsid", list.get(0));
		//得到全部图片
		List<Img> imglist = imgService.getImgById(map);
		// 过滤图片--分出商品展示图和商品详情图
		Map<String, List<Img>> imgmap = imgsFilter(imglist);
		 //准备--获取不同类型的图片材料
		List<Img> goodslist = (List<Img>) imgmap.get("goods");
		List<Img> detaillist = (List<Img>) imgmap.get("detail");
		List<String> goodsnamelist = new ArrayList<String>();
		List<String> detailnamelist = new ArrayList<String>();
		//获取图片名称
		getImgNames(detailnamelist, detaillist);
		getImgNames(goodsnamelist,goodslist);
		// 根据id获取包装
		List<Pakage> pakagelist = pakageService.getPackageListById(map);
		// 根据id获取口味
		List<Taste> tastelist = tasteService.getTasteListById(map);
		// 获取总销售量
		List<UserOrder> olist = getAllUserorderCount(map);
		// 获取当月销售量
		List<UserOrder> molist = getUserorderCountByMonth(map);
		// 获取商品属性
		Attribute attr = attributeService.getAttrByCon(map);
		// 设置评论查询条件
		HashMap<String, Integer> commentmap = new HashMap<String, Integer>();
		commentmap.put("goodsid", Integer.valueOf(list.get(0)));
		// 获取所有评论
		List<UserComment> commenlist = userCommentService.getAllComments(commentmap);
		// 好评、中评、差评
		int favor = 0, associ = 0, negative = 0;
		if (commenlist.size() != 0) {
			// 循环计数
			for (UserComment userComment : commenlist) {
				int level = userComment.getLevel();
				if (level == 1) {
					// 好评
					favor++;
				} else if (level == 2) {
					// 中评
					associ++;
				} else if (level == 3) {
					// 差评
					negative++;
				}
			}
		}
		if (goods != null) {
			// 商品
			session.setAttribute("goods", goods);
			// 商品详情图
			session.setAttribute("detailimgs", detailnamelist);
			// 商品图片
			session.setAttribute("goodsimgs", goodsnamelist);
			// 包装
			session.setAttribute("pakagelist", pakagelist);
			// 口味
			session.setAttribute("tastelist", tastelist);
			// 销售量
			session.setAttribute("olist", olist.size());
			// 月销售量
			session.setAttribute("molist", molist.size());
			// 商品属性
			session.setAttribute("attrbute", attr);
			// 评论
			// 所有评论
			session.setAttribute("comments", commenlist);
			// 所有评论数
			session.setAttribute("allcomm", commenlist.size());
			// 好评数
			session.setAttribute("favorcomm", favor);
			// 中评数
			session.setAttribute("associcomm", associ);
			// 差评数
			session.setAttribute("negativecomm", negative);
			result = "success";
		}
		return result;
	}

	/**
	 * 
	 * @Description:获取评论 void
	 * @exception:
	 * @author: "陈泓源"
	 * @time:2016年12月20日 下午12:04:39
	 */
	public void getComment() {
		response.setCharacterEncoding("utf-8");
		try {
			out = response.getWriter();
			// 获取商品id
			List<String> parlist = getPrameter("id", "index", "pagesize");
			String goodsid = parlist.get(0);
			HashMap<String, Integer> commentmap = new HashMap<String, Integer>();
			commentmap.put("goodsid", Integer.valueOf(goodsid));
			String pageindex = parlist.get(1);
			if (pageindex == null) {
				pageindex = "1";
			}
			// 获取所有评论
			List<UserComment> commenlist = userCommentService.getAllComments(commentmap);
			commentmap.put("pageindex", Integer.valueOf(pageindex));
			commentmap.put("pagesize", Integer.valueOf(parlist.get(2)));
			// 初始化page参数
			Page<List> page = new Page<List>();
			page.setPageIndex(Integer.valueOf(pageindex));
			page.setPageSize(Integer.valueOf(parlist.get(2)));
			page.setDataTotal(commenlist.size());
			int pagecount = (page.getDataTotal() % page.getPageSize()) == 0 ? (page.getDataTotal() / page.getPageSize())
					: (page.getDataTotal() / page.getPageSize() + 1);
			page.setPageCount(pagecount);
			// 分页查询所有评论
			List<UserComment> usercom = userCommentService.getUserCommentByPage(commentmap);
			List<User> users = new ArrayList<User>();
			List<Goods> goodses =new ArrayList<Goods>();
			List<String> datelist =new ArrayList<String>();
			for (UserComment userComment : usercom) {
				//处理日期格式
				SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD hh:mm:ss");
				String date = sdf.format(userComment.getComtime());
				datelist.add(date);
				//获取用户信息
				int userid = userComment.getUserId();
				int gid = userComment.getGoodsId();
				User user = new User();
				user.setId(userid);
				user = userService.getUser(user);
				users.add(user);
				//获取商品信息
				HashMap<String,Integer> map =new HashMap<String,Integer>();
				map.put("id", gid);
				Goods goods = new Goods();
				goods = goodsService.getGoodsByCondit(map);
				goodses.add(goods);
			}
			List<List> list  =new ArrayList<List>();
			list.add(usercom);
			list.add(users);
			list.add(goodses);
			list.add(datelist);
			page.setPageList(list);
			out.print(JSON.toJSONString(page));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			out.flush();
			out.close();
		}
	}
	/**
	 * 
	 * @Description:获取优惠券
	 * void
	 * @exception:
	 * @author: "陈泓源"
	 * @time:2016年12月21日 下午2:12:55
	 */
	public void getCoupons(){
		response.setCharacterEncoding("utf-8");
		try {
			out = response.getWriter();
			List<String> pralist = getPrameter("userid");
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("uid", pralist.get(0));
			List<Coupon> couponlist = couponService.getCoupons(map);
			out.print(JSON.toJSON(couponlist));
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			out.flush();
			out.close();
		}
	}
	/**
	 * 
	 * @Description:添加用户优惠券
	 * void
	 * @exception:
	 * @author: "陈泓源"
	 * @time:2016年12月21日 下午3:58:38
	 */
	public void addCoupons(){
		response.setCharacterEncoding("utf-8");
		boolean b= false;
		String outres = "err";
		try {
			out = response.getWriter();
			List<String> couponlist = getPrameter("cid","uid");
			HashMap<String, String> map =new HashMap<String, String>();
			map.put("cid", couponlist.get(0));
			map.put("uid", couponlist.get(1));
			b = userCouponService.addCoupons(map);
			if(b){
				outres="ok";
			}
			out.print(outres);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			out.flush();
			out.close();
		}
	}
	// -----------------------------用到的方法------------------------------------
	/**
	 * 
	 * @Description:获取图片的名称
	 * @param goods
	 * @param imgs
	 *            void
	 * @exception:
	 * @author: "陈泓源"
	 * @time:2016年12月19日 上午10:04:38
	 */
	private void getImgNames(List<String> goods, List<Img> imgs) {
		for (Img img : imgs) {
			String imgpath = img.getPath();
			String name = imgpath.substring(imgpath.lastIndexOf("/") + 1, imgpath.lastIndexOf("."));
			goods.add(name);
		}
	}

	/**
	 * 获取表单传输过来的参数
	 * 
	 * @param pra
	 * @return
	 */
	private List<String> getPrameter(String... pra) {
		List<String> list = new ArrayList<String>();
		for (String string : pra) {
			// 获取传输的参数
			list.add(request.getParameter(string));
		}
		return list;
	}

	/**
	 * 
	 * @Description:根据商品id查询销售量
	 * @param map
	 * @return List<UserOrder>
	 * @exception:
	 * @author: "陈泓源"
	 * @time:2016年12月15日 下午4:16:26
	 */
	private List<UserOrder> getAllUserorderCount(HashMap<String, String> map) {
		List<UserOrderItem> list = userOrderItemService.getUserOrderItemById(map);
		map.clear();
		String ids = "";
		int i = 1;
		for (UserOrderItem userOrderItem : list) {
			if (i < list.size()) {
				ids += userOrderItem.getOrderId() + ",";
			} else {
				ids += userOrderItem.getOrderId();
			}
			i++;
		}
		map.put("ids", ids);
		List<UserOrder> olist = userOrderServiceImpl.getUserOrderById(map);
		return olist;
	}

	/**
	 * 
	 * @Description:根据商品id查询当月销售量
	 * @param map
	 * @return List<UserOrder>
	 * @exception:
	 * @author: "陈泓源"
	 * @time:2016年12月15日 下午4:16:49
	 */
	private List<UserOrder> getUserorderCountByMonth(HashMap<String, String> map) {
		List<UserOrderItem> list = userOrderItemService.getUserOrderItemById(map);
		map.clear();
		String ids = "";
		int i = 1;
		for (UserOrderItem userOrderItem : list) {
			if (i < list.size()) {
				ids += userOrderItem.getOrderId() + ",";
			} else {
				ids += userOrderItem.getOrderId();
			}
			i++;
		}
		map.put("ids", ids);
		List<UserOrder> olist = userOrderServiceImpl.getUserOrderByIdAndMonth(map);
		return olist;
	}

	/**
	 * 
	 * @Description:过滤商品详情图片和商品显示图片
	 * @param list
	 * @return Map<String,List<Img>>
	 * @exception:
	 * @author: "陈泓源"
	 * @time:2016年12月15日 下午5:52:59
	 */
	private Map<String, List<Img>> imgsFilter(List<Img> list) {
		Map<String, List<Img>> map = new HashMap<String, List<Img>>();
		List<Img> detailimg = new ArrayList<Img>();
		List<Img> goodsimg = new ArrayList<Img>();
		for (Img img : list) {
			// 详情图片
			if (img.getPostion() == 1) {
				detailimg.add(img);
			} else if (img.getPostion() == 2) {// 商品图片
				goodsimg.add(img);
			}
		}
		map.put("detail", detailimg);
		map.put("goods", goodsimg);
		return map;
	}

}
